package com.heima.wemedia.interceptor;

import com.heima.utils.thread.WeMediaThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 陈辉
 * @data 2023 10:46
 * 性能测试，压力测试： jemeter
 * Q: 你们项目上线，服务器上有没有遇到过oom问题？    OutOfMemery【内存溢出】
 * A:
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if (!StringUtils.isBlank(userId)){
            //存入ThreadLocal
            WeMediaThreadLocalUtil.set(Integer.valueOf(userId));
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理ThreadLocal
        WeMediaThreadLocalUtil.clear();
    }
}
